package com.shishuo.cms.service;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shishuo.cms.constant.ExceptionConstant;
import com.shishuo.cms.dao.UserDao;
import com.shishuo.cms.entity.GoldEntity;
import com.shishuo.cms.entity.MyNetEntity;
import com.shishuo.cms.entity.UserEntity;
import com.shishuo.cms.entity.UserRoleEntity;
import com.shishuo.cms.entity.vo.PageVo;
import com.shishuo.cms.exception.AuthException;
import com.shishuo.cms.exception.LoginException;
import com.shishuo.cms.exception.RegException;
import com.shishuo.cms.util.AuthUtils;

@Service
public class UserService extends BaseService<UserEntity, Long> {

	private UserDao userDao;
	@Autowired
	private MailService mailService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private MyNetService myNetService;
	@Autowired
	private GoldService goldService;
	@Autowired
	private ConfigService configService;

	@Autowired
	public void setUserDao(UserDao userDao) {
		setBaseDao(userDao);
		this.userDao = userDao;
	}

	public UserEntity getSingleUser(String userName) {
		return userDao.getSingleUser(userName);
	}

	public int updateUserStatus(long id, int status) {
		return userDao.updateUserStatus(id, status);
	}

	public int delUsers(Integer[] userIds) {
		return userDao.delUsers(userIds);
	}

	public boolean existUser(String userName) {
		return userDao.existUser(userName);
	}

	public Integer add(UserEntity userEntity) throws Exception {
		if (existUser(userEntity.getUserName())) {
			throw new RegException(ExceptionConstant.REG_ERROR_USER_HAS_EXIST);
		}
		UserRoleEntity userRoleEntity = userRoleService.getByRoleName("普通用户");
		if (null != userRoleEntity) {
			userEntity.setRoleId(userRoleEntity.getId());
		}
		return userDao.add(userEntity);
	}

	public Integer innerReg(UserEntity userEntity, String referUserName,
			String centerUserName) throws Exception {
		if (existUser(userEntity.getUserName())) {
			throw new RegException(ExceptionConstant.REG_ERROR_USER_HAS_EXIST);
		}
		if (!existUser(referUserName)) {
			throw new RegException(
					ExceptionConstant.REG_ERROR_REF_USER_IS_NOT_EXIST);
		}
		if (!existUser(centerUserName)) {
			throw new RegException(
					ExceptionConstant.REG_ERROR_CENTER_USER_IS_NOT_EXIST);
		}
		UserEntity centerUser = userDao.getSingleUser(centerUserName);
		UserRoleEntity userRoleEntity = userRoleService.getById(centerUser
				.getRoleId());
		if (!userRoleEntity.getRoleName().equals("报单中心")) {
			throw new RegException(
					ExceptionConstant.REG_ERROR_CENTER_USER_IS_NOT_CORRECT);
		}
		UserRoleEntity userRoleEntity2 = userRoleService.getByRoleName("普通用户");
		if (null != userRoleEntity2) {
			userEntity.setRoleId(userRoleEntity2.getId());
		}
		return userDao.add(userEntity);
	}

	/*
	 * 通过用户名密码获取用户
	 */
	public UserEntity getByUserNameAndPassword(UserEntity userEntity)
			throws Exception {
		if (!existUser(userEntity.getUserName())) {
			throw new LoginException(
					ExceptionConstant.LOGIN_ERROR_USER_IS_NOT_EXIST);
		}
		UserEntity userEntityDb = this.getSingleUser(userEntity.getUserName());
		if (!userEntityDb.getPassWord().equals(userEntity.getPassWord())) {
			throw new LoginException(
					ExceptionConstant.LOGIN_ERROR_USERNAME_OR_PASS_IS_ERROR);
		}
		return userEntityDb;
	}

	public void updateUserPassword(UserEntity userEntity, String password,
			String oldpass) throws Exception {
		UserEntity userEntityDb = this.getSingleUser(userEntity.getUserName());
		if (null == userEntityDb || password == null || password.equals("")
				|| oldpass == null || oldpass.equals("")) {
			throw new Exception(ExceptionConstant.CHANGE_PASS_ERROR);
		}
		String pwd = AuthUtils.getPassword(password, userEntity.getUserName());
		String oldPwd = AuthUtils
				.getPassword(oldpass, userEntity.getUserName());
		if (!oldPwd.equals(userEntityDb.getPassWord())) {
			throw new Exception(
					ExceptionConstant.CHANGE_PASS_ERROR_OLD_PSD_ERROR);
		}
		userDao.updateUserPassword(userEntity.getId(), pwd);
	}

	public void updateUserExchangePassword(UserEntity userEntity,
			String password, String oldpass) throws Exception {
		UserEntity userEntityDb = this.getSingleUser(userEntity.getUserName());
		if (null == userEntityDb || password == null || password.equals("")
				|| oldpass == null || oldpass.equals("")) {
			throw new Exception(ExceptionConstant.CHANGE_PASS_ERROR);
		}
		String pwd = AuthUtils.getPassword(password, userEntity.getUserName());
		String oldPwd = AuthUtils
				.getPassword(oldpass, userEntity.getUserName());
		String oldLoginPwd = userEntityDb.getPassWord();
		if (null == userEntityDb.getChargePassWord()) {
			if (!oldLoginPwd.equals(oldPwd)) {
				throw new Exception(
						ExceptionConstant.CHANGE_PASS_ERROR_OLD_PSD_ERROR);
			}
		} else {
			if (!oldPwd.equals(userEntityDb.getChargePassWord())) {
				throw new Exception(
						ExceptionConstant.CHANGE_PASS_ERROR_OLD_PSD_ERROR);
			}
		}
		userDao.updateUserExchangePassword(userEntity.getId(), pwd);
	}

	/*
	 * 邮件找回密码
	 */
	public boolean sendMailForGetPassword(String emailpass) throws Exception {
		UserEntity userEntity = userDao.getSingleUserByEmail(emailpass);
		if (null == userEntity) {
			throw new Exception(ExceptionConstant.GET_PASSWORD_ERROR);
		}
		return mailService.sendCallBackPasswordMail(emailpass,
				userEntity.getUserName());
	}

	public PageVo<UserEntity> getAllListPage(int pageNum) throws Exception {
		PageVo<UserEntity> pageVo = new PageVo<UserEntity>(pageNum);
		List<UserEntity> list = this.getAllList(pageVo.getOffset(),
				pageVo.getRows());
		pageVo.setList(list);
		pageVo.setCount(this.getAllListCount());
		return pageVo;
	}

	// 加钱
	public int addUserMoney(long id, double money) {
		return userDao.updateAddUserMoney(id, money);
	}

	// 加金币
	public int addUserGold(long userId, double gold) throws Exception {
		GoldEntity entity = new GoldEntity();
		entity.setGoldCount(Math.abs(gold));
		entity.setGoldMsg(((gold > 0) ? "新增" : "扣除") + "金币");
		entity.setUserId(userId);
		entity.setPassMsg("操作成功");
		entity.setStatus(1);
		goldService.insert(entity);
		return userDao.updateAddUserGold(userId, gold);
	}

	public PageVo<UserEntity> getMyReferByUserName(String userName, int pageNum)
			throws Exception {
		PageVo<UserEntity> pageVo = new PageVo<UserEntity>(pageNum);
		List<UserEntity> list = userDao.getAllListByReferName(userName,
				pageVo.getOffset(), pageVo.getRows());
		pageVo.setList(list);
		pageVo.setCount(userDao.getAllListCountByReferName(userName));
		return pageVo;
	}

	public PageVo<UserEntity> getMyActiveUserByUserName(String userName,
			int pageNum) throws Exception {
		PageVo<UserEntity> pageVo = new PageVo<UserEntity>(pageNum);
		List<UserEntity> list = userDao.getMyActiveUserListByReferName(
				userName, pageVo.getOffset(), pageVo.getRows());
		pageVo.setList(list);
		pageVo.setCount(userDao.getMyActiveUserListCountByReferName(userName));
		return pageVo;
	}

	/**
	 * 激活用户
	 * 
	 * @param userId
	 * @param loginedUserEntity
	 * @throws Exception
	 */
	@Transactional
	public void activeUser(long userId, UserEntity loginedUserEntity,
			String parentUserName) throws Exception {
		double subGold = Double.valueOf(configService
				.getConfigByKey("SYS_SUB_GOLD"));
		double referPercent = Double.valueOf(configService
				.getConfigByKey("referPercent"));
		double pointParent = Double.valueOf(configService
				.getConfigByKey("pointParent"));// 点点积分比例
		double subPointParent = Double.valueOf(configService
				.getConfigByKey("subPointParent"));// 点点积分层级递减比例
		int positionNum = 0;// 设置挂接到父节点的左边还是右边
		int maxLevel = Integer
				.valueOf(configService.getConfigByKey("maxLevel"));// 点点比例深度
		UserEntity activeUserEntity = this.getById(userId);
		if (null == activeUserEntity) {
			throw new Exception(ExceptionConstant.ACTIVE_USER_ERROR);
		}
		if (activeUserEntity.getStatus() == 1) {
			throw new Exception(ExceptionConstant.ACTIVE_USER_HAS_ACTIVED);
		}
		UserEntity parentUserEntity = this.getSingleUser(parentUserName);
		if (null == parentUserEntity) {
			throw new Exception(
					ExceptionConstant.ACTIVE_PARIENT_USER_IS_NOT_EXIST);
		}
		if (parentUserEntity.getStatus() != 1) {
			throw new Exception(
					ExceptionConstant.ACTIVE_PARIENT_USER_IS_NOT_ACTIVED);
		}
		if (loginedUserEntity.getUserGold() < subGold) {
			throw new Exception(
					ExceptionConstant.ACTIVE_LOGINED_USER_HAS_NOT_ENOUGH_GOLD);
		}
		List<MyNetEntity> listMyNetEntity = myNetService
				.getMyNetEntityByParentUserName(parentUserName);
		if (listMyNetEntity.size() == 2) {
			throw new Exception(
					ExceptionConstant.ACTIVE_PARIENT_USER_HAS_TWO_CHILDEN);
		} else {
			if (listMyNetEntity.size() == 1) {
				positionNum = 1;
			}
		}
		MyNetEntity entity = new MyNetEntity();
		entity.setParentUserName(parentUserName);
		entity.setUserId(userId);
		entity.setPositionNum(positionNum);
		entity.setStatus(1);
		myNetService.insert(entity);
		// 扣除登录人的积分
		addUserGold(loginedUserEntity.getId(), 0 - subGold);// 减金币
		// 直接推荐人赚取积分
		UserEntity referUser = this.getSingleUser(activeUserEntity
				.getReferUserName());
		addUserGold(referUser.getId(), subGold * referPercent / 100);
		// 给上级用户加积分
		addUserGoldForParent(parentUserEntity, subGold * pointParent / 100,
				maxLevel, subPointParent);
		// 修改激活人状态为激活状态
		updateUserStatus(userId, 1);

	}

	private void addUserGoldForParent(UserEntity userEntity, double gold,
			int maxLevel, double subPointParent) throws Exception {
		addUserGold(userEntity.getId(), gold);// 给其上级加点
		UserEntity parentUserEntity = getParentUserByUserId(userEntity.getId());
		if ((null != parentUserEntity) && (maxLevel > 0)) {
			addUserGoldForParent(parentUserEntity, gold * subPointParent / 100,
					maxLevel--, subPointParent);
		}
	}

	private UserEntity getParentUserByUserId(long userId) {
		return userDao.getParentUserByUserId(userId);
	}

	@Transactional
	public void updateUserInfo(UserEntity userEntityDb, UserEntity newUserEntity)
			throws Exception {
		if (userEntityDb.getChargePassWord() == null) {
			String pwd = AuthUtils.getPassword(
					newUserEntity.getChargePassWord(),
					userEntityDb.getUserName());
			if (!pwd.equals(userEntityDb.getPassWord())) {
				throw new Exception(
						ExceptionConstant.CHANGE_USER_INFO_ERROR_CHARGE_PASSWORD_IS_NOT_CORRECT);
			}
			userEntityDb.setChargePassWord(pwd);
		} else {
			String pwd = AuthUtils.getPassword(
					newUserEntity.getChargePassWord(),
					userEntityDb.getUserName());
			if (!pwd.equals(userEntityDb.getChargePassWord())) {
				throw new Exception(
						ExceptionConstant.CHANGE_USER_INFO_ERROR_CHARGE_PASSWORD_IS_NOT_CORRECT);
			}
		}
		userEntityDb.setBankCard(newUserEntity.getBankCard());
		userEntityDb.setBankName(newUserEntity.getBankName());
		userEntityDb.setPhoneNum(newUserEntity.getPhoneNum());
		userEntityDb.setUserRealName(newUserEntity.getUserRealName());
		userEntityDb.setVertifyCard(newUserEntity.getVertifyCard());
		userDao.update(userEntityDb);
	}

	/**
	 * 增加用户冻结金额
	 * 
	 * @param userId
	 * @param outputMoney
	 */
	public void addUserForzenMoney(long userId, double outputMoney) {
		userDao.updateAddForzenUserMoney(userId, outputMoney);
	}

	public boolean existUserByOpenID(String qqOpenID) {
		return userDao.existUserByOpenID(qqOpenID);
	}

	public UserEntity getByQqOpenId(String qqOpenId) {
		return userDao.getByQqOpenId(qqOpenId);
	}

	public UserEntity addByOpenID(String openID, String nickname, String headImg)
			throws Exception {
		UserEntity userEntity = new UserEntity();
		userEntity.setQqOpenId(openID);
		userEntity.setHeadImg(headImg);
		userEntity.setNickName(nickname);
		userEntity.setUserName(getRandomUserName());
		userEntity.setPassWord("123456");// 默认密码为123456
		userEntity.setPassWord(AuthUtils.getPassword(userEntity.getPassWord(),
				userEntity.getUserName()));
		userEntity.setRoleId(1);
		userEntity.setStatus(1);
		insert(userEntity);
		return getById(userEntity.getId());
	}

	/**
	 * 随机用户名生成
	 * 
	 * @return
	 */
	private String getRandomUserName() {
		return "a5q6"+getRandomString(6);
	}
	public static String getRandomString(int length) {
		StringBuffer buffer = new StringBuffer(
				"0123456789abcdefghijklmnopqrstuvwxyz");
		StringBuffer sb = new StringBuffer();
		Random random = new Random();
		int range = buffer.length();
		for (int i = 0; i < length; i++) {
			sb.append(buffer.charAt(random.nextInt(range)));
		}
		return sb.toString();
	}
	//更新用户信息，通过QQ的openId
	public UserEntity updateUserByOpenID(long id, String openID,
			String nickname, String headImg) throws Exception {
		UserEntity userEntity=getById(id);
		userEntity.setQqOpenId(openID);
		userEntity.setNickName(nickname);
		userEntity.setHeadImg(headImg);
		update(userEntity);
		return userEntity;
	}
}